package com.example.myfirstmobile.custom.data;

import com.example.myfirstmobile.ResourceTable;
import com.example.myfirstmobile.custom.categorylist.HeadItem;
import com.example.myfirstmobile.custom.categorylist.SearchItem;
import com.example.myfirstmobile.custom.categorylist.SingleListItem;
import com.example.myfirstmobile.custom.categorylist.CategoryItemFactory;
import com.example.myfirstmobile.custom.categorylist.TestCategory;
import com.example.myfirstmobile.datamodel.Category;
import com.example.myfirstmobile.datamodel.CategoryItemBase;
import com.example.myfirstmobile.slice.MainAbilitySlice;
import com.example.myfirstmobile.views.adapter.CategoryListItemProvider;
import com.google.gson.Gson;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;
import ohos.utils.zson.ZSONArray;
import ohos.utils.zson.ZSONException;
import ohos.utils.zson.ZSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * Some custom data to display.
 */
public class CustomData {
    private static final int[][] CATEGORY_DATA = new int[][]{
            {SearchItem.ITEM_TYPE},
            {HeadItem.ITEM_TYPE, SingleListItem.ITEM_TYPE},
            {HeadItem.ITEM_TYPE, SingleListItem.ITEM_TYPE, SingleListItem.ITEM_TYPE},
//            {HeadItem.ITEM_TYPE, SingleListItem.ITEM_TYPE, SingleListItem.ITEM_TYPE, SingleListItem.ITEM_TYPE},
//            {HeadItem.ITEM_TYPE, SingleListItem.ITEM_TYPE, SingleListItem.ITEM_TYPE, SingleListItem.ITEM_TYPE,
//                    SingleListItem.ITEM_TYPE},
//            {HeadItem.ITEM_TYPE, SingleListItem.ITEM_TYPE, SingleListItem.ITEM_TYPE, SingleListItem.ITEM_TYPE,
//                    SingleListItem.ITEM_TYPE, SingleListItem.ITEM_TYPE},
//            {HeadItem.ITEM_TYPE, SingleListItem.ITEM_TYPE, SingleListItem.ITEM_TYPE, SingleListItem.ITEM_TYPE,
//                    SingleListItem.ITEM_TYPE, SingleListItem.ITEM_TYPE, SingleListItem.ITEM_TYPE},
    };

    private static int[][] CATEGORY_DATA2 = new int[4][4];

    private static final String CATEGORY_TEXT = "Category";

    private static final String SINGLE_LEFT_TEXT = "single list";

    private static final String SINGLE_RIGHT_TEXT = "right text";

    //设置日志的label
    private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG"); //MY_MODULE=0x00201

    public static void getRemoteCustomData(Context context) {
        TaskDispatcher globalTaskDispatcher = context.getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        globalTaskDispatcher.asyncDispatch(new Runnable() {
            @Override
            public void run() {
                NetManager netManager = NetManager.getInstance(null);

                if (!netManager.hasDefaultNet()) {
                    return;
                }
                NetHandle netHandle = netManager.getDefaultNet();

// 可以获取网络状态的变化
                NetStatusCallback callback = new NetStatusCallback() {
                    // 重写需要获取的网络状态变化的override函数
                };
                netManager.addDefaultNetStatusCallback(callback);

// 通过openConnection来获取URLConnection
                HttpURLConnection connection = null;
                try {
//                    String urlString = "http://124.71.206.112:8081/getData";
//                    URL url = new URL(urlString);
//
//                    URLConnection urlConnection = netHandle.openConnection(url,
//                            java.net.Proxy.NO_PROXY);
//                    if (urlConnection instanceof HttpURLConnection) {
//                        connection = (HttpURLConnection) urlConnection;
//                    }
//                    connection.setRequestMethod("GET");
//                    connection.connect();
//                    HiLog.info(label, "Get Preferences value %{public}s", connection);
//                    // 之后可进行URL的其他操作
//                    int responseCode = connection.getResponseCode();
//                    if(responseCode == HttpURLConnection.HTTP_OK){
//                        //得到响应流
//                        InputStream inputStream = connection.getInputStream();
//                        //将响应流转换成字符串
//                        String result = is2String(inputStream);//将流转换为字符串。
//                        HiLog.info(label, "Get Preferences value %{public}s", result);
//                        CATEGORY_DATA2=json2Array(result);
//                    }
////If you cannot connect the server, please use mockdata to instead.
                    String mockResult = "{\"data\":[\n" +
                            "\t{\"items\":[1]},\n" +
                            "\t{\"items\":[3,2]},\n" +
                            "\t{\"items\":[3,2,2]},\n" +
                            "\t{\"items\":[3,2,2,2]}\n" +
                            "]}";

                    CATEGORY_DATA2=json2Array(mockResult);

                    TaskDispatcher uiTaskDispatcher = context.getUITaskDispatcher();
                    uiTaskDispatcher.asyncDispatch(() -> {
                        ArrayList<Category> categoryList = new ArrayList<>();
                        for (int i = 0; i < CATEGORY_DATA2.length; i++) {
                            int[] items = CATEGORY_DATA2[i];
                            ArrayList<CategoryItemBase> itemList = new ArrayList<>();
                            for (int j = 0; j < items.length; j++) {
                                switch (items[j]) {
                                    case HeadItem.ITEM_TYPE:
                                        itemList.add(CategoryItemFactory.createListItem(context, HeadItem.ITEM_TYPE,
                                                CATEGORY_TEXT + i));
                                        break;
                                    case SingleListItem.ITEM_TYPE:
                                        itemList.add(CategoryItemFactory.createListItem(context, SingleListItem.ITEM_TYPE,
                                                SINGLE_LEFT_TEXT + j, SINGLE_RIGHT_TEXT));
                                        break;
                                    case SearchItem.ITEM_TYPE:
                                        itemList.add(CategoryItemFactory.createListItem(context, SearchItem.ITEM_TYPE));
                                        break;
                                    default:
                                        break;
                                }
                            }
                            TestCategory testCategory = new TestCategory(context, itemList, i);
                            categoryList.add(testCategory);

                            Component mainComponent = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_main_ability,
                                    null, false);

                            CategoryListItemProvider categoryListItemProvider = new CategoryListItemProvider(categoryList);

                            ListContainer listContainer = (ListContainer) mainComponent.findComponentById(ResourceTable.Id_list_view);
                            if (listContainer != null) {
                                listContainer.setItemProvider(categoryListItemProvider);
                            }
                            ((MainAbilitySlice)context).setUIContent((ComponentContainer) mainComponent);
                        }
                    });

                } catch(Exception e) {
                    e.printStackTrace();
                } finally {
                    if(connection!=null)
                        connection.disconnect();
                }
            }

            public String is2String(InputStream is){
                String response=null;
                try {
                    //连接后，创建一个输入流来读取response
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));

                    String line;
                    StringBuilder stringBuilder = new StringBuilder();
                    response = "";
                    //每次读取一行，若非空则添加至 stringBuilder
                    while((line = bufferedReader.readLine()) != null){
                        stringBuilder.append(line);
                    }
                    //读取所有的数据后，赋值给 response
                    response= stringBuilder.toString().trim();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return response;
            }


            int[][] json2Array(String s){
                HiLog.info(label, "HTTP Response: " + s);

                CustomDataObject customDataObject = ZSONObject.stringToClass(s, CustomDataObject.class);
                CustomDataItem[] customDataItems = customDataObject.getData();

                int[][] customDataArray = new int[4][4];
                int i=0,j=0;

                for(CustomDataItem customDataItem :customDataItems){
                    for(int item : customDataItem.getItems()){
                        customDataArray[i][j]=item;
                        System.out.println("item"+item);
                        j++;
                    }
                    i++;j=0;
                }

                return customDataArray;
            }

        });
        HiLog.info(label, "Outside thread");


    }
    /**
     * Return some custom data to display.
     *
     * @param context current context
     * @return custom category list
     */
    public static List<Category> getCustomData(Context context) {

        ArrayList<Category> categoryList = new ArrayList<>();
        for (int i = 0; i < CATEGORY_DATA.length; i++) {
            int[] items = CATEGORY_DATA[i];
            ArrayList<CategoryItemBase> itemList = new ArrayList<>();
            for (int j = 0; j < items.length; j++) {
                switch (items[j]) {
                    case HeadItem.ITEM_TYPE:
                        itemList.add(CategoryItemFactory.createListItem(context, HeadItem.ITEM_TYPE,
                                CATEGORY_TEXT + i));
                        break;
                    case SingleListItem.ITEM_TYPE:
                        itemList.add(CategoryItemFactory.createListItem(context, SingleListItem.ITEM_TYPE,
                                SINGLE_LEFT_TEXT + j, SINGLE_RIGHT_TEXT));
                        break;
                    case SearchItem.ITEM_TYPE:
                        itemList.add(CategoryItemFactory.createListItem(context, SearchItem.ITEM_TYPE));
                        break;
                    default:
                        break;
                }
            }
            TestCategory testCategory = new TestCategory(context, itemList, i);
            categoryList.add(testCategory);
        }
        return categoryList;
    }

}
